<script lang="ts" setup>
import type {
  TooltipComponentOption,
  GridComponentOption,
  GraphicComponentOption,
  LineSeriesOption,
  ComposeOption,
  DefaultLabelFormatterCallbackParams,
  ToolboxComponentOption,
} from 'echarts';

import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
import { TooltipComponent, GridComponent, GraphicComponent, ToolboxComponent } from 'echarts/components';
import { SVGRenderer } from 'echarts/renderers';
import { UniversalTransition } from 'echarts/features';
import { ref, onMounted, nextTick, onUnmounted } from 'vue';
import { $fetch } from '@/settings/utils/fetch';
import { isBefore, isAfter, format, sub } from 'date-fns';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
// 通过 ComposeOption 来组合出一个只有必须组件和图表的 Option 类型
type ECOption = ComposeOption<
  | LineSeriesOption
  | TooltipComponentOption
  | GridComponentOption
  | GraphicComponentOption
  | ToolboxComponentOption
>;

// 注册必须的组件
echarts.use([
  TooltipComponent,
  GridComponent,
  GraphicComponent,
  LineChart,
  SVGRenderer,
  UniversalTransition,
  ToolboxComponent,
]);

export interface AnyObject {
  [key: string]: unknown;
}

export interface ToolTipFormatterCallbackParams extends DefaultLabelFormatterCallbackParams {
  axisDim: string;
  axisIndex: number;
  axisType: string;
  axisId: string;
  axisValue: string;
  axisValueLabel: string;
}

const START_DATE = new Date(2024, 3, 1); // 2024-04-01

const chartEl = ref();
const loading = ref(false);
const xAxis = ref<string[]>([]);
const chartsData = ref<number[]>([]);
const detail = ref<Record<string, any[]>>({});
const currentKey = ref('pv');
const dateRange = ref([format(sub(new Date(), { days: 14 }), 'yyyy-MM-dd'), format(new Date(), 'yyyy-MM-dd')]);

const graphicFactory = (side: AnyObject) => {
  return {
    type: 'text',
    bottom: '8',
    ...side,
    style: {
      text: '',
      textAlign: 'center',
      fill: '#4E5969',
      fontSize: 12,
    },
  };
};

const graphicElements = ref([
  graphicFactory({ left: '2.6%' }),
  graphicFactory({ right: 0 }),
]);

const option: ECOption = {
  grid: {
    left: '2.6%',
    right: '2.6%',
    top: '10',
    bottom: '30',
  },
  toolbox: {
    feature: {
      saveAsImage: {
        show: true,
        title: t('settings.view.welcome.save'),
      },
    },
  },
  xAxis: {
    type: 'category',
    offset: 2,
    boundaryGap: false,
    axisLabel: {
      color: '#4E5969',
      rich: {
        today: {
          color: '#2d2d2d',
          fontWeight: 'bold',
        },
      },
    },
    axisLine: {
      show: false,
    },
    axisTick: {
      show: false,
    },
    splitLine: {
      show: true,
      lineStyle: {
        color: '#E5E8EF',
      },
    },
    axisPointer: {
      show: true,
      lineStyle: {
        color: '#23ADFF',
        width: 2,
      },
    },
  },
  yAxis: {
    type: 'value',
    axisLine: {
      show: false,
    },
    minInterval: 1,
    splitLine: {
      show: true,
      lineStyle: {
        type: 'dashed',
        color: '#E5E8EF',
      },
    },
  },
  tooltip: {
    trigger: 'axis',
    formatter(params) {
      const [firstElement] = params as ToolTipFormatterCallbackParams[];
      return `<div>
<p class="tooltip-title">${firstElement.axisValueLabel}</p>
<div class="content-panel"><span class="tooltip-value">${firstElement.value}</span></div>
</div>`;
    },
    className: 'echarts-tooltip-diy',
  },
  graphic: {
    elements: graphicElements.value,
  },
  series: [
    {
      data: [],
      type: 'line',
      smooth: true,
      symbolSize: 12,
      emphasis: {
        focus: 'series',
        itemStyle: {
          borderWidth: 2,
        },
      },
      lineStyle: {
        width: 3,
        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
          {
            offset: 0,
            color: 'rgba(30, 231, 255, 1)',
          },
          {
            offset: 0.5,
            color: 'rgba(36, 154, 255, 1)',
          },
          {
            offset: 1,
            color: 'rgba(111, 66, 251, 1)',
          },
        ]),
      },
      showSymbol: false,
      areaStyle: {
        opacity: 0.8,
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: 'rgba(17, 126, 255, 0.16)',
          },
          {
            offset: 1,
            color: 'rgba(17, 128, 255, 0)',
          },
        ]),
      },
    },
  ],
};

let chartInstance: echarts.ECharts;

const refresh = async () => {
  const { isSuccess, data } = await $fetch('/admin/record/history', {
    method: 'post',
    data: {
      startDate: dateRange.value[0],
      endDate: dateRange.value[1],
    },
    loadingStatus: loading,
  });

  if (isSuccess) {
    detail.value = data;

    setData();
  }
}

const setData = () => {
  xAxis.value = [];
  chartsData.value = [];

  Array.from(detail.value[currentKey.value]).reverse().forEach((item: Record<string, any>) => {
    xAxis.value.push(item.x);
    chartsData.value.push(item.y);
  });

  chartInstance.setOption({
    xAxis: {
      data: xAxis.value,
      splitLine: {
        interval: (idx: number) => {
          if (idx === 0) { return false; }
          if (idx === xAxis.value.length - 1) { return false; }
          return true;
        },
      },
    },
    series: [{
      data: chartsData.value,
    }],
  });
}

onMounted(async () => {
  await nextTick();

  chartInstance = echarts.init(chartEl.value, null, { renderer: 'svg' });
  chartInstance.setOption(option);

  refresh();

  if (window.ResizeObserver) {
    const resizeObserver = new ResizeObserver(() => {
      chartInstance.resize();
    });

    resizeObserver.observe(chartEl.value);
  }
});

onUnmounted(() => {
  chartInstance?.dispose();
});
</script>

<template>
  <ASpin :loading="loading" class="w-full">
    <OpenGeneralCard :title="$t('settings.view.welcome.general.title')">
      <div class="mb-20 ml-15 mr-50 flex-y-center flex-wrap justify-between gap-y-10">
        <div>
          <ARadioGroup v-model="currentKey" @change="setData">
            <ARadio value="pv">
              <template #radio="{ checked }">
                <ATag :checked="checked" color="blue" checkable>{{ $t('settings.view.welcome.general.column1') }}</ATag>
              </template>
            </ARadio>
            <ARadio value="uv">
              <template #radio="{ checked }">
                <ATag :checked="checked" color="blue" checkable>{{ $t('settings.view.welcome.general.column2') }}</ATag>
              </template>
            </ARadio>
            <ARadio value="newUser">
              <template #radio="{ checked }">
                <ATag :checked="checked" color="blue" checkable>{{ $t('settings.view.welcome.general.column3') }}</ATag>
              </template>
            </ARadio>
            <ARadio value="active">
              <template #radio="{ checked }">
                <ATag :checked="checked" color="blue" checkable>{{ $t('settings.view.welcome.general.column4') }}</ATag>
              </template>
            </ARadio>
            <ARadio value="newWarehouse">
              <template #radio="{ checked }">
                <ATag :checked="checked" color="blue" checkable>{{ $t('settings.view.welcome.general.column5') }}</ATag>
              </template>
            </ARadio>
            <ARadio value="newOrg">
              <template #radio="{ checked }">
                <ATag :checked="checked" color="blue" checkable>{{ $t('settings.view.welcome.general.column6') }}</ATag>
              </template>
            </ARadio>
            <ARadio value="newCommit">
              <template #radio="{ checked }">
                <ATag :checked="checked" color="blue" checkable>{{ $t('settings.view.welcome.general.column7') }}</ATag>
              </template>
            </ARadio>
            <ARadio value="newIssue">
              <template #radio="{ checked }">
                <ATag :checked="checked" color="blue" checkable>{{ $t('settings.view.welcome.general.column8') }}</ATag>
              </template>
            </ARadio>
            <ARadio value="newRequireChange">
              <template #radio="{ checked }">
                <ATag :checked="checked" color="blue" checkable>{{ $t('settings.view.welcome.general.column9') }}</ATag>
              </template>
            </ARadio>
          </ARadioGroup>
        </div>

        <div>
          <ARangePicker v-model="dateRange" disabled-input :allow-clear="false" :disabled-date="(current: Date) => isBefore(current, START_DATE) || isAfter(current, new Date())" @change="refresh" />
        </div>
      </div>
      <div class="h-310px" ref="chartEl"></div>
    </OpenGeneralCard>
  </ASpin>
</template>

<style lang="scss" scoped>
</style>
